package com.bolt.admin.module.quartz.service;

import com.bolt.admin.module.quartz.dto.JobDTO;
import com.bolt.admin.module.quartz.dto.converter.JobConverter;
import com.bolt.admin.module.quartz.entity.JobEntity;
import com.bolt.admin.module.quartz.repository.JobRepository;
import com.bolt.convention.exception.ServiceException;
import com.bolt.support.base.service.BaseService;
import com.bolt.support.spring.jpa.repository.BasicJpaRepository;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Auto Generate Javadoc
 *
 * @author 日期:2020-09-29 11:12:32
 *         定时任务
 **/
@Service
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class JobService extends BaseService <JobEntity, Long> {

    @Autowired
    private JobRepository jobRepository;

    @Autowired
    private QuartzManage quartzManage;

    @Override
    protected BasicJpaRepository <JobEntity, Long> getRepository() {
        return jobRepository;
    }

    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(JobDTO jobDTO) {
        if (!CronExpression.isValidExpression(jobDTO.getCronExpression())) {
            throw new ServiceException("cron表达式格式错误");
        }
        JobEntity entity = JobConverter.toEntity(jobDTO);
        if(entity.isNew()){
            save(entity);
            quartzManage.addJob(entity);
        }else{
            save(entity);
            quartzManage.updateJob(entity);
        }

    }


    public void updateIsPause(JobEntity quartzJob) {
        if (quartzJob.getIsPause()) {
            quartzManage.resumeJob(quartzJob);
            quartzJob.setIsPause(false);
        } else {
            quartzManage.pauseJob(quartzJob);
            quartzJob.setIsPause(true);
        }
        save(quartzJob);
    }


}
